import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../screens/home/model/comic_category_item_model.dart';
import '../utils/http_helper.dart';

// ComicCategoryData 状态管理
final comicCategoryProvider = StateNotifierProvider.family<ComicCategoryNotifier, AsyncValue<List<ComicCategoryData>>, String>((ref, categoryId) {
  return ComicCategoryNotifier(categoryId);
});

class ComicCategoryNotifier extends StateNotifier<AsyncValue<List<ComicCategoryData>>> {
  final String categoryId;
  
  ComicCategoryNotifier(this.categoryId) : super(const AsyncValue.loading()) {
    _loadData();
  }
  
  Future<void> _loadData() async {
    try {
      state = const AsyncValue.loading();
      
      final userResponse = await HttpUtil().getModel<List<ComicCategoryData>>(
        'Comic/GetComicCategoriesSortList',
        params: {"categoryId": categoryId},
        fromJson: (json) => (json as List)
            .map((item) => ComicCategoryData.fromJson(item))
            .toList(),
      );
      
      if (userResponse?.status == 200 && userResponse?.result != null) {
        state = AsyncValue.data(userResponse!.result!);
      } else {
        state = AsyncValue.error('Failed to load data', StackTrace.current);
      }
    } catch (error, stackTrace) {
      state = AsyncValue.error(error, stackTrace);
    }
  }
  
  Future<void> refresh() async {
    await _loadData();
  }
}